#coding=UTF-8
from SocketServer import ThreadingTCPServer, TCPServer, ThreadingMixIn, StreamRequestHandler
from ISO8583.ISO8583 import ISO8583
from ISO8583.ISOErrors import *
import struct

def Define(iso):
    iso.redefineBit(7,'7','TraceCode','N',2,'ans')
    iso.redefineBit(11,'11','JourNo','N',8,'n')
    iso.redefineBit(12,'12','Time','N',6,'n')
    iso.redefineBit(13,'13','Date','N',8,'n')
    iso.redefineBit(15,'15','ClearDate','N',8,'n')
    iso.redefineBit(20,'20','TXN_FLAG','N',8,'ans')
    iso.redefineBit(22,'22','SERVENTRY','N',3,'n')
    iso.redefineBit(25,'25','SERVCODE','N',2,'n')
    iso.redefineBit(32,'32','DealCode','N',11,'ans')
    iso.redefineBit(33,'33','SendCode','N',11,'ans')
    iso.redefineBit(37,'37','RetrievalRefNbr','N',12,'ans')
    iso.redefineBit(39,'39','RespCode','N',2,'ans')
    iso.redefineBit(41,'41','TERMID','N',8,'ans')
    iso.redefineBit(42,'42','TRANBRANCH','N',15,'ans')
    iso.redefineBit(43,'43','CUSTOMNAME','LL',40,'ans')
    iso.redefineBit(46,'46','ZHE','N',10,'ans')
    iso.redefineBit(49,'49','CurrenceNO','N',3,'ans')
    iso.redefineBit(53,'53','SECUINFO','N',16,'n')
    iso.redefineBit(100,'100','RecvCode','N',11,'ans')
    #iso.redefineBit(123,'123','SELF1','LLL',40,'ans')
    #iso.redefineBit(128,'128','MAC1','B',8,'b')

def SetValue(iso):
    iso.setMTI('0830')
    iso.setBit(2,'607310001210347207')
    iso.setBit(3,'883030')  
    iso.setBit(4,'000000013242') 
    iso.setBit(7,'16')
    iso.setBit(11,'00000001')
    iso.setBit(12,'151600')
    iso.setBit(13,'20100909')
    iso.setBit(15,'20100910')
    iso.setBit(20,'10000000')
    iso.setBit(22,'011')
    iso.setBit(25,'00')
    iso.setBit(28,'00000000') 
    iso.setBit(29,'00000000') 
    iso.setBit(32,'5301009    ')
    iso.setBit(33,'5301009    ')
    iso.setBit(37,'37643329    ')
    iso.setBit(39,'00')
    iso.setBit(41,'00095580')
    iso.setBit(42,'000000530111020')
    iso.setBit(43,'name')
    iso.setBit(49,'156')
    iso.setBit(53,'1120000000000000')
    iso.setBit(100,'531003     ')  
    iso.setBit(103,'18987092901')
    iso.setBit(123,'YYYYYYYYYY000000013242007000560002107')
    
def BeforeSend(message):
    deal = message[4:36]
    l = list()
    for i in range(0,32,2):
        l.append(deal[i:i+2])
    m_s=""
    for j in l:
        m_s = m_s + struct.pack('!h', int(j,16))[1:]
    
    message=message[0:4] + m_s + message[36:]
    
    message = '0000001' + '00000001' + '0000' + message
    netIso =  struct.pack('!h', len(message))
    netIso = netIso + message
    return netIso

def getISO():
    iso = ISO8583()
    Define(iso)
    SetValue(iso)
    set1 = struct.pack('!h', 23)
    set2 = struct.pack('!h', 24)
    set3 = struct.pack('!h', 25)
    set4 = struct.pack('!h', 26)
    set = set1 + set2 + set3 + set4
    #iso.setBit(128,set)  # 报文鉴别码
    v1 = iso.getBitsAndValues()
    for v in v1:
        print 'Bit %s of type %s with value = %s' % (v['bit'],v['type'],v['value'])
    return iso.getRawIso()

class Handler(StreamRequestHandler):
    def handle(self):
        while 1:
            addr = self.request.getpeername()
            print 'Got connection from', addr
            chunk = self.connection.recv(2)
            if len(chunk) < 2:
                break
            hlen = chunk
            slen = struct.unpack("!h", chunk)[0]
            chunk = self.connection.recv(slen)
            while len(chunk) < slen:
                chunk = chunk + self.connection.recv(slen - len(chunk))
            print '----raw---------------'
            print chunk
            #print 'len: %d' % slen + 'pack:%s ' % struct.pack('!h', len(chunk))
            isoContent = ReceivedDeal(hlen + chunk)
            print '----received----------'
            print isoContent
            iso = ISO8583()
            Define(iso)
            iso.setIsoContent(isoContent)
            v1 = iso.getBitsAndValues()
            for v in v1:
                print 'Bit %s of type %s with value = %s' % (v['bit'],v['type'],v['value'])
            print '----end----------'
            message = getISO()
            netIso = BeforeSend(message)
            print netIso
            self.wfile.write(netIso)

#class Server(ThreadingMixIn, TCPServer): pass
class SocketReceiver(ThreadingTCPServer):
    """simple TCP socket-based logging receiver suitable for testing.
    """

    allow_reuse_address = 1

    def __init__(self, host='127.0.0.1',
                 port=6787,
                 handler=Handler):
        ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None

    def serve_until_stopped(self):
        import select
        abort = 0
        while not abort:
            rd, wr, ex = select.select([self.socket.fileno()],
                                       [], [],
                                       self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort

def ReceivedDeal(ans):
    print '--------ans-----------'
    print ans
    size = struct.unpack('!h',ans[0:2])[0]
    print '-------size-----------'
    print size
    systemid = ans[2:9]
    print '-------systemid-------'
    print systemid
    journo = ans[9:17]
    print '-------journo---------'
    print journo
    errorno = ans[17:21]
    print '-------errorno--------'
    print errorno
    type = ans[21:25]
    print '-------type-----------'
    print type
    
    pbiso = ans[25:int(size)-21+25]
    #bitmap = pbiso[0:16]
    
    isobitmap = ''
    for i in range(0, 16):
        tmp = '\x00' + pbiso[i]
        isobitmap += '%02x' % struct.unpack('!h', tmp)[0]
    
    isoContent = type + isobitmap + pbiso[16:]
    
    return isoContent

#server = Server(('', 10030), Handler)
#server.serve_forever()
def main():
    tcpserver = SocketReceiver()
    print 'starting...'
    tcpserver.serve_until_stopped()
if __name__ == "__main__":
    main()